package com.sais.manage.boot.platform.storage;


import com.sais.manage.boot.platform.entity.Throttle;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class ThrottleCodeStorage {

    private static Map<String, Map<String, Throttle>> THROTTLE_CODES = new HashMap<>();
    private static int TOTAL = 3;

    public static boolean hasThrottleCode(String sessionId, String throttleCode) {
        Map<String, Throttle> sessionIdMap = THROTTLE_CODES.get(sessionId);
        if (CollectionUtils.isEmpty(sessionIdMap)) {
            return false;
        }
        Throttle throttle = sessionIdMap.get(throttleCode);
        if (StringUtils.isEmpty(throttle)) {
            return false;
        }
        if (throttle.getExpiredTime().isBefore(LocalDateTime.now())) {
            THROTTLE_CODES.get(sessionId).remove(throttleCode);
            return false;
        } else {
            int count = throttle.getCount();
            if (count <= TOTAL) {
                throttle.setCount(count++);
                sessionIdMap.put(throttleCode, throttle);
                THROTTLE_CODES.put(sessionId, sessionIdMap);
                return false;
            } else {
                return true;
            }
        }
    }

    public static boolean setThrottleCode(String sessionId, String throttleCode, Long second) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime plusSeconds = now.plusSeconds(second);
        Map<String, Throttle> sessionIdMap = THROTTLE_CODES.get(sessionId);
        if (StringUtils.isEmpty(sessionIdMap)) {
            sessionIdMap = new HashMap<>(32);
        }
        Throttle throttle = sessionIdMap.get(throttleCode);
        if (StringUtils.isEmpty(throttle)) {
            throttle = new Throttle();
            throttle.setCount(1);
            throttle.setExpiredTime(plusSeconds);
        } else {
            throttle.setCount(throttle.getCount() + 1);
        }
        sessionIdMap.put(throttleCode, throttle);
        THROTTLE_CODES.put(sessionId, sessionIdMap);
        return true;
    }

    public static boolean removeThrottleCode(String sessionId, String throttleCode) {
        Map<String, Throttle> stringThrottleMap = THROTTLE_CODES.get(sessionId);
        if (CollectionUtils.isEmpty(stringThrottleMap)) {
            return true;
        }
        stringThrottleMap.remove(throttleCode);
        return true;
    }


}
